package com.projects.android.views;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.projects.android.R;
import com.projects.android.adapters.RestaurantsAdapter;
import com.projects.android.dto.FoodDTO;
import com.projects.android.dto.MenuDTO;
import com.projects.android.dto.RestaurantDTO;
import com.projects.android.utils.SelectedItems;
import com.projects.android.utils.Utils;

public class ListRestaurant extends ListActivity {
	private Intent intent;
	private TextView lblDistrict;
	private TextView lblFoodType;
	private TextView lblCity;
	public static ArrayList<RestaurantDTO> Restaurants;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lstrestaurant);
		initFrm();
	}

	private void initFrm() {
		lblCity = (TextView) findViewById(R.id.lblCity);
		lblCity.setText(SelectedItems.SelectedCity.getName());

		lblDistrict = (TextView) findViewById(R.id.lblDistrict);
		lblDistrict.setText(SelectedItems.SelectedDistrict.getName());

		lblFoodType = (TextView) findViewById(R.id.lblFoodType);
		lblFoodType.setText(SelectedItems.SelectedFoodtype.getName());

		if (Restaurants != null) {
			RestaurantsAdapter adapter = new RestaurantsAdapter(this,
					R.layout.restaurantitem, R.id.lblRestaurantName,
					Restaurants);
			setListAdapter(adapter);
			getListView().setTextFilterEnabled(true);
		}
	}

	private ArrayList<FoodDTO> loadFoods(RestaurantDTO restaurant) {
		ArrayList<FoodDTO> result = new ArrayList<FoodDTO>();
		ArrayList<MenuDTO> menus = restaurant.getMenus();
		for (MenuDTO menu : menus) {
			ArrayList<FoodDTO> foods = menu.getFoods();
			for (FoodDTO food : foods) {
				// Set menu name for each food item
				food.setMenuName(menu.getName());
				result.add(food);
			}
		}
		return result;
	}

	public void onListItemClick(ListView parent, View v, int pos, long id) {
		if (pos >= 0 && pos < Restaurants.size()) {
			final RestaurantDTO restaurant = Restaurants.get(pos);

			final ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle("Loading. Please wait...");
			dialog.setIndeterminate(true);

			final Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						ArrayList<FoodDTO> data = loadFoods(restaurant);

						@Override
						public void run() {
							SelectedItems.SelectedRestaurant = restaurant;
							SelectedItems.AllFoods = data;
							intent = Utils.browseIntent(ListRestaurant.this,
									"RestaurantFoods");
							startActivity(intent);
							dialog.dismiss();
						}
					});
				}
			});
			dialog.show();
			thread.start();
		}
	}
}
